from typing import Optional
from pydantic import BaseModel, EmailStr, Field, validator
from datetime import datetime
from app.shared.constants.enums import UserRole


class UserBase(BaseModel):
    """用户基础信息"""
    username: str = Field(..., min_length=3, max_length=50, description="用户名")
    full_name: Optional[str] = Field(None, max_length=100, description="全名")
    email: Optional[EmailStr] = Field(None, description="邮箱")
    phone: Optional[str] = Field(None, regex=r'^1[3-9]\d{9}$', description="手机号")
    role: UserRole = Field(UserRole.USER, description="用户角色")
    is_active: bool = Field(True, description="是否激活")


class UserCreate(UserBase):
    """创建用户"""
    password: str = Field(..., min_length=6, max_length=20, description="密码")
    
    @validator('password')
    def validate_password(cls, v):
        if not any(c.isalpha() for c in v):
            raise ValueError('密码必须包含至少一个字母')
        if not any(c.isdigit() for c in v):
            raise ValueError('密码必须包含至少一个数字')
        return v


class UserUpdate(BaseModel):
    """更新用户信息"""
    full_name: Optional[str] = Field(None, max_length=100, description="全名")
    email: Optional[EmailStr] = Field(None, description="邮箱")
    phone: Optional[str] = Field(None, regex=r'^1[3-9]\d{9}$', description="手机号")
    avatar_url: Optional[str] = Field(None, description="头像URL")
    is_active: Optional[bool] = Field(None, description="是否激活")


class UserUpdateRole(BaseModel):
    """更新用户角色"""
    role: UserRole = Field(..., description="用户角色")


class UserChangePassword(BaseModel):
    """修改密码"""
    old_password: str = Field(..., description="旧密码")
    new_password: str = Field(..., min_length=6, max_length=20, description="新密码")
    
    @validator('new_password')
    def validate_new_password(cls, v):
        if not any(c.isalpha() for c in v):
            raise ValueError('新密码必须包含至少一个字母')
        if not any(c.isdigit() for c in v):
            raise ValueError('新密码必须包含至少一个数字')
        return v


class UserResponse(UserBase):
    """用户响应信息"""
    id: int = Field(..., description="用户ID")
    avatar_url: Optional[str] = Field(None, description="头像URL")
    last_login_at: Optional[datetime] = Field(None, description="最后登录时间")
    created_at: datetime = Field(..., description="创建时间")
    updated_at: datetime = Field(..., description="更新时间")
    
    class Config:
        from_attributes = True


class UserLogin(BaseModel):
    """用户登录"""
    username: str = Field(..., description="用户名")
    password: str = Field(..., description="密码")
    remember_me: bool = Field(False, description="记住我")


class UserLoginResponse(BaseModel):
    """登录响应"""
    access_token: str = Field(..., description="访问令牌")
    refresh_token: str = Field(..., description="刷新令牌")
    token_type: str = Field("bearer", description="令牌类型")
    expires_in: int = Field(..., description="过期时间(秒)")
    user: UserResponse = Field(..., description="用户信息")


class UserRefreshToken(BaseModel):
    """刷新令牌"""
    refresh_token: str = Field(..., description="刷新令牌")


class UserProfile(UserResponse):
    """用户档案"""
    work_order_stats: Optional[dict] = Field(None, description="工单统计")
    recent_activities: Optional[list] = Field(None, description="最近活动")


class UserListQuery(BaseModel):
    """用户列表查询"""
    page: int = Field(1, ge=1, description="页码")
    page_size: int = Field(20, ge=1, le=100, description="每页数量")
    search: Optional[str] = Field(None, description="搜索关键词")
    role: Optional[UserRole] = Field(None, description="角色筛选")
    is_active: Optional[bool] = Field(None, description="激活状态筛选")
    sort_by: Optional[str] = Field("created_at", description="排序字段")
    sort_order: Optional[str] = Field("desc", regex=r'^(asc|desc)$', description="排序方向")